const { app, BrowserWindow, Tray, Menu, ipcMain, dialog, globalShortcut: global_shortcut, nativeImage } = require('electron');
const fs = require('fs')

const path = require('path');
const isDev = process.env.NODE_ENV === 'development';

const sort = (a, b) => {
  if (a.type != b.type) {
    return b.type - a.type
  } else {
    return a.name - b.name
  }
}

const getFiles = (dir) => {
  let fileList = [];
  const list = fs.readdirSync(dir);
  for (let i = 0; i < list.length; i++) {
    const item = path.resolve(dir, list[i])
    let type = 0;
    const obj = {
      name: item.replace(dir + '\\', ''),
      path: item,
      parentPath: dir
    }
    if (fs.statSync(item).isDirectory()) {
      if (item.indexOf("node_modules") >= 0) {
        continue;
      }
      //文件夹
      fileList = fileList.concat(getFiles(item))
      type = 1
    }

    fileList.push({
      ...obj,
      type
    })
  }
  return fileList;
}

const defaultOps = {
  id: '', //唯一id
  title: '', //窗口标题
  width: '', //宽度
  height: '', //高度
  minWidth: '', //最小宽度
  minHeight: '', //最小高度
  x: '', // 窗口相对于屏幕左侧坐标
  y: '', // 窗口相对于屏幕顶端坐标
  route: '', // 页面路由URL '/manage?id=123'
  resizable: true, //是否支持调整窗口大小
  maximize: false, //是否最大化
  backgroundColor:'#eee', //窗口背景色
  skipTaskbar: false,
  data: null, //数据
  isMultiWindow: false, //是否支持多开窗口 (如果为false，当窗体存在，再次创建不会新建一个窗体 只focus显示即可，，如果为true，即使窗体存在，也可以新建一个)
  isMainWin: false, //是否主窗口(当为true时会替代当前主窗口)
  parentId: '', //父窗口id  创建父子窗口 -- 子窗口永远显示在父窗口顶部 【父窗口可以操作】
  modal: false, //模态窗口 -- 模态窗口是禁用父窗口的子窗口，创建模态窗口必须设置 parent 和 modal 选项 【父窗口不能操作】
  alwaysOnTop: false
};

class WindowApp {
  main;
  group;
  tray;

  constructor() {
    this.main = null;
    this.group = {};
    this.tray = null;
  }

  winOpts(w, h, args) {
    return {
      frame: false,
      transparent: false,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        plugins: true,
        webSecurity: false,
        allowDisplayingInsecureContent: true,
        allowRunningInsecureContent: true,
        enableRemoteModule: true,
        preload: path.resolve(path.join(__dirname, 'preload.js')),
      },
      icon: path.join(__dirname, '../src/assets/favicon.ico'),
      width: w,
      height: h,
    }
  }

  getWindow(id) {
    return BrowserWindow.fromId(Number(id))
  }

  currentWindow(){
    return BrowserWindow.getFocusedWindow()
  }

  getAllWindows() {
    return BrowserWindow.getAllWindows();
  }

  createWindow(options) {
    const args = Object.assign({}, defaultOps, options);
    for (const i in this.group) {
      if (this.getWindow(i) && this.group[i].route === args.route && !this.group[i].isMultiWindow) {
        this.getWindow(i).focus();
        return;
      }
    }
    const opt = this.winOpts(args.width || 800, args.height || 600 ,args);
    if (args.parentId) {
      opt.parent = this.getWindow(args.parentId);
    } else if (this.main) {

    }
    if (typeof args.modal === 'boolean') opt.modal = args.modal;
    if (typeof args.resizable === 'boolean') opt.resizable = args.resizable;
    if (typeof args.alwaysOnTop === 'boolean') opt.alwaysOnTop = args.alwaysOnTop
    if (args.backgroundColor) opt.backgroundColor = args.backgroundColor;
    if (args.width) opt.width = args.width
    if (args.height) opt.height = args.height
    if (args.minWidth) opt.minWidth = args.minWidth;
    if (args.minHeight) opt.minHeight = args.minHeight;
    if (args.x) opt.x = args.x
    if (args.y) opt.y = args.y
    if (args.transparent !== null){
      opt.transparent = args.transparent
    }
    if(args.skipTaskbar !== null){
      opt.skipTaskbar = args.skipTaskbar
    }
    if(args.alwaysOnTop !== null){
      opt.alwaysOnTop = args.alwaysOnTop;
    }
    console.log(opt);
    const win = new BrowserWindow(opt);
    this.group[win.id] = {
      route: args.route,
      isMultiWindow: args.isMultiWindow
    };
    //是否最大化
    if (args.maximizable && args.resizable) {
      win.maximize();
    }
    console.log(opt.x, opt.y)
    if(opt.x && opt.y){
      win.setPosition(opt.x, opt.y)
    }
    if (args.isMainWin) {
      if (this.main) {
        delete this.group[this.main.id]
        if (!this.main.isDestroyed()) {
          this.main.close();
        }
      }
      this.main = win;
    }

    win.on('close', () => win.setOpacity(0))

    if (isDev) {
      win.loadURL(`http://127.0.0.1:3000/#${options.route || '/'}`);
    } else {
      win.loadFile('dist/index.html', {
        hash: options.route
      })
    }

    win.hookWindowMessage(278, function(e){
      win.setEnabled(false)
      setTimeout(() => {
          win.setEnabled(true)
      }, 100)

      return true
    })
  }

  closeAllWindow() {
    for (const i in this.group) {
      if (this.group[i]) {
        if (this.getWindow(i)) {
          this.getWindow(i).close();
        } else {
          app.quit();
        }
      }
    }
    
  }

  createTray() {
    const contextMenu = Menu.buildFromTemplate([
      {
        label: '显示',
        click: () => {
          for (const i in this.group) {
            if (this.group[i]) {
              const win = this.getWindow(i);
              if (!win) return;
              if (win.isMinimized()) win.restore();
              win.show();
            }
          }
        }
      },
      {
        label: '退出',
        click: () => {
          app.quit();
        }
      }
    ]);

    const trayIco = path.join(__dirname, '../src/assets/favicon.ico');
    this.tray = new Tray(trayIco);
    this.tray.setContextMenu(contextMenu);
    this.tray.setToolTip(app.name);
  }

  listen() {
    //关闭
    ipcMain.on('window-closed', (event, current) => {
      this.currentWindow().close();
    });

    //隐藏
    ipcMain.on('window-hide', (event, winId) => {
      this.currentWindow().hide();
    });

    //显示
    ipcMain.on('window-show', (event) => {
      this.currentWindow().show();
    })

    //最小化
    ipcMain.on('window-mini', (event) => {
      this.currentWindow().minimize();
    });

    //最大化
    ipcMain.on('window-max', (event) => {
      this.currentWindow().maximize();
    });

    //最大化/最小化
    ipcMain.on('window-max-min-size', (event) => {
      const currentWin = this.currentWindow();
      if (currentWin) {
        if (currentWin.isMaximized()) {
          currentWin.unmaximize();
        } else {
          currentWin.maximize();
        }
      }
    });

    //还原
    ipcMain.on('window-restore', (event) => {
      this.currentWindow().restore();
    });

    //重新加载
    ipcMain.on('window-reload', (event) => {
      this.currentWindow().reload();
    });

    //透明区域穿透
    ipcMain.on('ignoreMouse', (e, arg) => {
      if(arg){
        this.currentWindow().setIgnoreMouseEvents(true,{ forward: true })
      }else{
        this.currentWindow().setIgnoreMouseEvents(false)
      }
    })

    ipcMain.on('openDialog', (event) => {
      const currentWin = this.currentWindow();
      if (!currentWin) {
        return
      }
      dialog.showOpenDialog({
        properties: ['openDirectory'],
      }).then(result => {
        const { canceled, filePaths } = result;
        if (!canceled) {
          const dir = filePaths[0];
          let list = getFiles(dir);
          const dirList = dir.split('\\');
          const rootPath = dirList.filter((o, i) => i < dirList.length - 1).join('\\')
          const root = {
            name: dirList[dirList.length - 1],
            path: dir,
            parentPath: rootPath,
            type: 1
          }
          list.push(root)
          list = list.sort(sort)
          const obj = {
            root,
            data: list
          }
          currentWin.webContents.send('openFiles', JSON.stringify(obj))
        }
      })
    })

    // 创建窗口
    ipcMain.on('window-new', (event, args) => this.createWindow(args));
  }
}

module.exports = WindowApp